package com.service.words;

import com.dto.NoteDto;
import com.dto.WordsDto;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mapper.generator.ShWordsMapper;
import com.mapper.self.NoteMapper;
import com.mapper.self.WordsMapper;
import com.pojo.ShCompany;
import com.pojo.ShWords;
import com.service.user.UserService;
import com.utils.DateUtils;
import com.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Huoyunren on 2016-06-24.
 */
@Service
public class WordsServiceImpl implements WordsService {
  @Autowired
  private ShWordsMapper shWordsMapper;
  @Autowired
  private WordsMapper wordsMapper;
  @Autowired
  private UserService userService;
  @Autowired
  private NoteMapper noteMapper;

  @Override
  public Object add(String from, String to, String content) {
    ShWords words = new ShWords();
    Date now = DateUtils.currentDate();
    words.setSourceEmail(from);
    words.setDesEmail(to);
    words.setContent(content);
    words.setCreateTime(now);
    words.setUuid(RandomUtils.getUuid());
    shWordsMapper.insert(words);
    NoteDto noteDto = new NoteDto();
    ShCompany company = userService.info(to);
    noteDto.setCreateTime(DateUtils.getFormatDate("", now));
    noteDto.setUuid(words.getUuid());
    noteDto.setContent(content);
    noteDto.setName(company.getName());
    noteDto.setLogo(company.getLogo());
    noteDto.setEmail(to);
    return noteDto;
  }

  @Override
  public Object list(Integer pageNo, Integer pageSize, String to) {
    if (pageNo == null) {
      pageNo = 1;
    }
    if (pageNo > 0) {
      pageNo -= 1;
    }
    if (pageSize == null) {
      pageSize = 10;
    }
    List<WordsDto> list = wordsMapper.list(pageNo * pageSize, pageSize, to);
    if (CollectionUtils.isEmpty(list)) {
      return list;
    }
    Set<String> uuids = Sets.newHashSet();
    for (WordsDto wordsDto : list) {
      uuids.add(wordsDto.getUuid());
    }
    if (CollectionUtils.isEmpty(uuids)) {
      return list;
    }
    List<NoteDto> notes = noteMapper.queryByUuid(uuids);
    if (CollectionUtils.isEmpty(notes)) {
      return list;
    }
    Map<String/*uuid*/, List<NoteDto>> map = Maps.newHashMap();
    for (NoteDto note : notes) {
      note.setCreateTime(note.getCreateTime().substring(0, note.getCreateTime().length() - 2));
      if (!map.containsKey(note.getUuid())) {
        map.put(note.getUuid(), Lists.<NoteDto>newArrayList());
      }
      map.get(note.getUuid()).add(note);
    }
    for (WordsDto wordsDto : list) {
      wordsDto.setNotes(map.get(wordsDto.getUuid()));
    }
    return list;
  }
}
